//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.views.websocket;

import cn.hutool.json.JSONUtil;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/api/viewsManage/websocket/views/{id}")
public class IviewWebSocketViews {
    private static final Logger log = LoggerFactory.getLogger(IviewWebSocketViews.class);
    private static ConcurrentHashMap<String, IviewWebSocketViews> webSocketMap = new ConcurrentHashMap();
    private Session session;

    public static void sendMessage(Object message, String sessionIdAndId) {
        IviewWebSocketViews webSocket = (IviewWebSocketViews)webSocketMap.get(sessionIdAndId);
        if (webSocket != null && webSocket.session.isOpen()) {
            try {
                webSocket.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
                log.debug("【websocket消息】发送消息成功,连接=" + sessionIdAndId + ",消息内容" + message.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            webSocketMap.remove(sessionIdAndId);
        }

    }

    public static ConcurrentHashMap<String, IviewWebSocketViews> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(ConcurrentHashMap<String, IviewWebSocketViews> webSocketMap) {
        IviewWebSocketViews.webSocketMap = webSocketMap;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.session = session;
        webSocketMap.put(session.getId() + "@" + id, this);
        log.debug("【websocket消息】有新的连接,连接：" + id + " 总数:" + webSocketMap.size());
    }

    @OnClose
    public void onClose(Session session, @PathParam("id") String id) {
        webSocketMap.remove(session.getId() + "@" + id);
        log.debug("【websocket消息】连接断开,总数:" + webSocketMap.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.debug("【websocket消息】收到客户端发来的消息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.debug("【websocket消息】非正常关闭,发生错误!:" + error.toString());
    }
}
